package com.iot.ammeter.service.impl.web.campus;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iot.ammeter.dto.web.campus.CampusInfoDTO;
import com.iot.ammeter.dto.web.campus.SchoolNameAndCampusNameDTO;
import com.iot.ammeter.entity.web.campus.Building;
import com.iot.ammeter.entity.web.campus.Campus;
import com.iot.ammeter.exception.BusinessExceptions;
import com.iot.ammeter.mapper.web.campus.BuildingMapper;
import com.iot.ammeter.mapper.web.campus.CampusMapper;
import com.iot.ammeter.query.web.campus.CampusQuery;
import com.iot.ammeter.service.web.campus.CampusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.ammeter.utils.CheckTool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import com.iot.ammeter.utils.SnowFlakeIdWorker;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 校区 服务实现类
 * </p>
 *
 * @author basil
 * @since 2021-09-25
 */
@Service
public class CampusServiceImpl extends ServiceImpl<CampusMapper, Campus> implements CampusService {

    private final CampusMapper campusMapper;
    private final SnowFlakeIdWorker snowFlakeIdWorker;
    private final BuildingMapper buildingMapper;

    public CampusServiceImpl(CampusMapper campusMapper, SnowFlakeIdWorker snowFlakeIdWorker, BuildingMapper buildingMapper) {
        this.campusMapper = campusMapper;
        this.snowFlakeIdWorker = snowFlakeIdWorker;
        this.buildingMapper = buildingMapper;
    }

    /**
     * 获取校区及校区名
     *
     * @return 返回树形校区及校区名
     */
    @Override
    public Map<String, List<SchoolNameAndCampusNameDTO>> getSchoolNameAndCampusName() {
        Map<String, List<SchoolNameAndCampusNameDTO>> map = new HashMap<>();
        List<SchoolNameAndCampusNameDTO> schoolNameAndCampusNameDTOList = campusMapper.selectSchoolNameAndCampusName();
        schoolNameAndCampusNameDTOList.forEach(item -> {
            map.put(item.getSchoolName(), item.getChildren());
        });
        return map;
    }

    /**
     * 获取学校信息列表
     *
     * @param page        请求页码
     * @param pageSize    每页数量
     * @param campusQuery 查询条件
     * @return ResponseResult
     */
    @Override
    public IPage<Campus> getCampusList(int page, int pageSize, CampusQuery campusQuery) {

        //封装page对象
        Page<Campus> pages = new Page<>(page, pageSize);
        //查询
        IPage<Campus> campusIPage = campusMapper.listCampus(pages, campusQuery);
        return campusIPage;
    }

    /**
     * 添加校区信息
     *
     * @param campusInfoDTO 校区信息
     * @return 添加成功或者失败提示
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addCampus(CampusInfoDTO campusInfoDTO) {


        String schoolName = campusInfoDTO.getSchoolName();
        String campusName = campusInfoDTO.getCampusName();
        String campusAddress = campusInfoDTO.getCampusAddress();
        String contactPerson = campusInfoDTO.getContactPerson();
        String phone = campusInfoDTO.getPhone();
        String providerId = campusInfoDTO.getProviderId();
        String fax = campusInfoDTO.getFax();
        String email = campusInfoDTO.getEmail();
        String logo = campusInfoDTO.getLogo();
        String provinceCityArea = campusInfoDTO.getProvinceCityArea();
        if (StringUtils.isEmpty(schoolName) || StringUtils.isEmpty(campusName) ||
                StringUtils.isEmpty(campusAddress) || StringUtils.isEmpty(contactPerson) ||
                StringUtils.isEmpty(phone) || StringUtils.isEmpty(providerId) ||
                StringUtils.isEmpty(fax) || StringUtils.isEmpty(email) ||
                StringUtils.isEmpty(logo) || StringUtils.isEmpty(provinceCityArea)) {
            throw new BusinessExceptions("校区信息存在空字段");
        }
        if (!CheckTool.isPhone(phone)) {
            throw new BusinessExceptions("手机号码非法");
        }
        if (!CheckTool.isEmail(email)) {
            throw new BusinessExceptions("邮箱格式有误");
        }
        /**
         * 判断校区是否存在
         */
        if (campusMapper.campusExists(schoolName, campusName) != null) {
            throw new BusinessExceptions("校区已存在");
        }

        /**
         * 补全数据
         */
        Campus campusToDb = new Campus();
        campusToDb.setCampusId(String.valueOf(snowFlakeIdWorker.nextId()));
        campusToDb.setSchoolName(schoolName);
        campusToDb.setCampusName(campusName);
        campusToDb.setCampusAddress(campusAddress);
        campusToDb.setContactPerson(contactPerson);
        campusToDb.setPhone(phone);
        campusToDb.setIsDeleted(0);
        campusToDb.setCreateTime(LocalDateTime.now());
        campusToDb.setUpdateTime(LocalDateTime.now());
        campusToDb.setProviderId(providerId);
        campusToDb.setFax(fax);
        campusToDb.setEmail(email);
        campusToDb.setLogo(logo);
        campusToDb.setProvinceCityArea(provinceCityArea);
        /**
         * 插入数据库
         */
        int result = campusMapper.insert(campusToDb);
        return result > 0 ? "添加校区成功" : "添加校区失败";
    }

    /**
     * 编辑/更新校区信息
     *
     * @param campusId      校区id
     * @param campusInfoDTO 校区信息
     * @return 编辑成功或者编辑失败提示
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String editCampus(String campusId, CampusInfoDTO campusInfoDTO) {

        String schoolName = campusInfoDTO.getSchoolName();
        String campusName = campusInfoDTO.getCampusName();
        String campusAddress = campusInfoDTO.getCampusAddress();
        String contactPerson = campusInfoDTO.getContactPerson();
        String phone = campusInfoDTO.getPhone();
        String providerId = campusInfoDTO.getProviderId();
        String fax = campusInfoDTO.getFax();
        String email = campusInfoDTO.getEmail();
        String logo = campusInfoDTO.getLogo();
        String provinceCityArea = campusInfoDTO.getProvinceCityArea();
        if (!CheckTool.isPhone(phone) && !StringUtils.isEmpty(phone)) {
            throw new BusinessExceptions("手机号码非法");
        }
        if (!CheckTool.isEmail(email) && !StringUtils.isEmpty(email)) {
            throw new BusinessExceptions("邮箱格式有误");
        }

        /**
         * 补全数据
         */
        Campus campusToDb = new Campus();
        campusToDb.setCampusId(campusId);
        campusToDb.setSchoolName(schoolName);
        campusToDb.setCampusName(campusName);
        campusToDb.setCampusAddress(campusAddress);
        campusToDb.setContactPerson(contactPerson);
        campusToDb.setPhone(phone);
        campusToDb.setIsDeleted(1);
        campusToDb.setCreateTime(LocalDateTime.now());
        campusToDb.setUpdateTime(LocalDateTime.now());
        campusToDb.setProviderId(providerId);
        campusToDb.setFax(fax);
        campusToDb.setEmail(email);
        campusToDb.setLogo(logo);
        campusToDb.setProvinceCityArea(provinceCityArea);
        /**
         * 插入数据库
         */
        int result = campusMapper.updateById(campusToDb);
        return result > 0 ? "更新校区成功" : "更新校区失败";
    }

    /**
     * 删除校区信息
     *
     * @param campusId 校区id
     * @return ResponseResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String delCampus(String[] campusId) {
        //查询该校区下是否有楼栋信息，存在则删除失败
        Integer count = buildingMapper.selectCount(new LambdaQueryWrapper<Building>().in(Building::getCampusId, Arrays.asList(campusId)));
        if (count > 0) {
            throw new BusinessExceptions("删除失败，所删除的校区下含有楼栋信息。");
        }
        int result = campusMapper.deleteBatchIds(Arrays.asList(campusId));
        return result > 0 ? "成功删除" + result + "条" : "校区删除失败";
    }

    /**
     * 获取校区详细信息
     *
     * @param campusId 校区id
     * @return ResponseResult
     */
    @Override
    public CampusInfoDTO getCampusDetails(String campusId) {
        CampusInfoDTO campusFromDb = campusMapper.getCampusDetailsById(campusId);
        return campusFromDb;
    }

}
